'use strict';

const { Surveys, Questions, Answers, UserJoins, SurveyState, Users } = require('../models');
const auth = require('../utils/auth');

function getTime(time) {
    let date = new Date(time);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    return (y + '-' + m + '-' + d);
};

let rootindex_fn = async (ctx, next) => {
    ctx.render('rootIndex.html')
}

let rootHome_fn = async (ctx, next) => {
    // 用户数量
    let usercount = JSON.parse(JSON.stringify(await Users.count({
        where: {
            role: 1,
        }
    })));
    // 活跃用户
    let userActivecount = JSON.parse(JSON.stringify(await Users.count({
        where: {
            role: 1,
            isActive: 1,
            isDelete: 0
        }
    })));

    //问卷数量
    let surveycount = JSON.parse(JSON.stringify(await Surveys.count()));

    let nowTime = getTime(Date.now());
    // 每日新增用户
    let users = JSON.parse(JSON.stringify(await Users.findAll({
        where: {
            role: 1,
            isActive: 1,
            isDelete: 0
        }
    })));

    let dayUserCount = 0;
    users.forEach(item => {
        let creTime = getTime(JSON.parse(item.createdAt));

        if (nowTime === creTime) {
            dayUserCount += 1;
        } else {
            dayUserCount = 0;
        }
    });

    //每日新增创建问卷数量
    let surveys = JSON.parse(JSON.stringify(await Surveys.findAll({
        where: {
            isActive: 1,
            isDelete: 0
        }
    })));

    let daySurveyCount = 0;
    surveys.forEach(item => {
        let creTime = getTime(JSON.parse(item.createdAt));

        if (nowTime === creTime) {
            daySurveyCount += 1;
        } else {
            daySurveyCount = 0;
        }
    });

    //每日新增发布问卷数量
    let surveystate = JSON.parse(JSON.stringify(await SurveyState.findAll({
        where: {
            state: 1,
            isActive: 1,
            isDelete: 0
        }
    })));

    let dayStateCount = 0;
    surveystate.forEach(item => {
        let creTime = getTime(JSON.parse(item.createdAt));

        if (nowTime === creTime) {
            dayStateCount += 1;
        } else {
            dayStateCount = 0;
        }
    });


    let obj = {
        usercount,
        userActivecount,
        surveycount,
        dayUserCount,
        daySurveyCount,
        dayStateCount
    }

    ctx.render('rootHtml/home.html', obj)
}

let root_updatePwd_fn = async (ctx, next) => {
    ctx.render('rootHtml/updatePwd.html')
}

// 所有用户
let userpage_fn = async (ctx, next) => {

    let users = JSON.parse(JSON.stringify(await Users.findAll({
        where: {
            role: 1,
        }
    })));

    users.forEach(item => {
        if (item.isActive === "1") {
            item.isActivelabel = "活跃"
        } else {
            item.isActivelabel = "已冻结"
        }
        if (item.isDelete === "1") {
            item.isDeletelabe = "已删除"
        } else {
            item.isDeletelabe = ""
        }

        item.createTime = getTime(JSON.parse(item.createdAt));
    })

    let obj = {
        users,
    }

    ctx.render('rootHtml/userPage.html', obj)
}

// 未发布问卷
let unpublish_fn = async (ctx, next) => {
    let stateArr = [];

    // 0为未发布
    let surveystate = JSON.parse(JSON.stringify(await SurveyState.findAll({
        where: {
            state: 0
        }
    })));

    surveystate.forEach(item => {
        stateArr.push(item.surveyId);
    });

    let survey = JSON.parse(JSON.stringify(await Surveys.findAll({
        where: {
            id: stateArr
        }
    })));

    let user = JSON.parse(JSON.stringify(await Users.findAll({
        where: {
            role: 1
        }
    })));

    survey.forEach(item => {
        let u = user.filter(man => {
            return man.id === item.userId
        })[0];

        if (item.isDelete === "1") {
            item.isDeletelabe = "已删除"
        } else {
            item.isDeletelabe = ""
        }
        item.name = u === undefined ? '匿名' : u.username;
        item.createTime = getTime(JSON.parse(item.createdAt));
    });

    let obj = {
        survey
    }
    ctx.render('rootHtml/unpublishPage.html', obj)
}

//已发布问卷
let publish_fn = async (ctx, next) => {
    let stateArr = [];
    let surveyArr = [];

    // 0为未发布
    let surveystate = JSON.parse(JSON.stringify(await SurveyState.findAll({
        where: {
            state: 1
        }
    })));

    surveystate.forEach(item => {
        stateArr.push(item.surveyId);
    });


    let survey = JSON.parse(JSON.stringify(await Surveys.findAll({
        where: {
            id: stateArr
        }
    })));

    survey.forEach(item => {
        surveyArr.push(item.id)
    })

    let user = JSON.parse(JSON.stringify(await Users.findAll({
        where: {
            role: 1
        }
    })));


    let userjoin = JSON.parse(JSON.stringify(await UserJoins.count({
        where: {
            surveryId: surveyArr
        },
        attributes: ['surveryId'],
        group: 'surveryId',
    })));


    survey.forEach(item => {
        let u = user.filter(man => {
            return man.id === item.userId
        })[0];

        let join = userjoin.filter(num => {
            return num.surveryId === item.id
        })[0];

        item.usercount = join === undefined ? 0 : join.count

        if (item.isDelete === "1") {
            item.isDeletelabe = "已删除"
        } else {
            item.isDeletelabe = ""
        }
        item.name = u === undefined ? '匿名' : u.username;
        item.createTime = getTime(JSON.parse(item.createdAt));
    });

    let obj = {
        survey
    }
    ctx.render('rootHtml/publishPage.html', obj)
}

// 修改密码
let updatePwd_judge_fn = async (ctx, next) => {
    let pwd = ctx.request.body.password.trim();
    let repwd = ctx.request.body.repassword.trim();
    let userId = ctx.session.userId;

    let res = "";
    if (pwd === repwd) {
        await Users.update({ password: pwd }, {
            where: {
                id: userId
            }
        });

        res = { code: 200, msg: '修改成功' };
    } else {
        res = { code: 400, msg: '两次密码不一致，请重新输入' };
    }

    ctx.body = JSON.stringify(res);
}

//删除用户
let userpage_remove_fn = async (ctx, next) => {
    let userId = ctx.request.body.removeId;

    await Users.update({ isDelete: 1 }, {
        where: {
            id: userId
        }
    });

    ctx.body = { code: 200, msg: "删除成功" }
}

//冻结用户
let userpage_ice_fn = async (ctx, next) => {
    let userId = ctx.request.body.iceId;

    await Users.update({ isActive: 0 }, {
        where: {
            id: userId
        }
    });

    ctx.body = { code: 200, msg: "冻结成功" }
}

let surveypage_remove_fn = async (ctx, next) => {
    let surveyId = ctx.request.body.removeId;

    await Surveys.update({ isDelete: 1 }, {
        where: {
            id: surveyId
        }
    });

    await SurveyState.update({ isDelete: 1 }, {
        where: {
            id: surveyId
        }
    });

    ctx.body = { code: 200, msg: "删除成功" }

}

// 未发布问卷问题详情
let unpublish_question_fn = async (ctx, next) => {
    let id = ctx.params.id;

    let question = JSON.parse(JSON.stringify(await Questions.findAll({
        where: {
            serveyId: id
        }
    })));


    let obj = {
        question
    }
    ctx.render('rootHtml/unpublishQuestion.html', obj)
}

let publish_question_fn = async (ctx, next) => {
    let id = ctx.params.id;
    let userIdArr = [];
    let questionNum = [];

    let question = JSON.parse(JSON.stringify(await Questions.findAll({
        where: {
            serveyId: id
        }
    })));

    let answer = JSON.parse(JSON.stringify(await Answers.findAll({
        where: {
            surveryId: id
        }

    })));

    answer.forEach(item => {
        questionNum.push(item.questionNumber)
        userIdArr.push(item.userId);
    });


    let newArr = [];
    for (var i = 0; i < userIdArr.length; i++) {
        if (newArr.indexOf(userIdArr[i]) === -1) {
            newArr.push(userIdArr[i]);
        }
    };

    let user = JSON.parse(JSON.stringify(await Users.findAll({
        where: {
            id: newArr
        }
    })));


    let sumList = [];
    user.forEach(u => {
        let answers = answer.filter(a => {
            return a.userId === u.id
        });
        // 得分情况


        let sum = 0;
        answers.forEach(item => {
            let num = parseInt(item.score)
            sum += num
        })
        sumList.push(sum)

        u.answers = answers;
        u.count = sum
    })



    let obj = {
        question,
        answer,
        user,

    }
    ctx.render('rootHtml/publishQuestion.html', obj)
}
module.exports = {
    '/rootindex': ['get', auth, rootindex_fn],
    '/rootHome': ['get', auth, rootHome_fn],
    '/root/updatePwd': ['get', auth, root_updatePwd_fn],
    '/root/updatePwd/judge': ['post', updatePwd_judge_fn],
    '/root/userpage': ['get', auth, userpage_fn],
    '/root/unpublish': ['get', auth, unpublish_fn],
    '/root/publish': ['get', auth, publish_fn],
    '/userpage/remove': ['post', userpage_remove_fn],
    '/userpage/ice': ['post', userpage_ice_fn],
    '/surveyp/remove': ['post', surveypage_remove_fn],
    '/root/unpublishQuestion/:id': ['get', auth, unpublish_question_fn],
    '/root/publishQuestion/:id': ['get', auth, publish_question_fn],
}
